package gateIo

import (
	"errors"
	"fmt"
	"gitee.com/jinmingzhi/block-chain-news/model"
	"github.com/antchfx/htmlquery"
	"go.uber.org/zap"
	"net/http"
	"strings"
	"time"
)

var url = "https://gate1.opencoding.com/cn/articlelist/ann/0"

type gateIo struct {
	name       string
	newArticle string
	timer      time.Duration
}

func NewGateIo(t time.Duration) *gateIo {
	return &gateIo{
		name:       "gate.io",
		newArticle: "",
		timer:      t,
	}
}

func (h *gateIo) Monitor(articleChan chan<- model.Msg) {
	h.newArticle, _ = h.getArticle()
	log.Info(fmt.Sprintf("%s: %s", h.name, h.newArticle))

	go func() {
		t := time.NewTicker(h.timer)
		for range t.C {
			str, err := h.getArticle()
			if err != nil {
				continue
			}
			if str != h.newArticle {
				h.newArticle = str
				articleChan <- model.Msg{OriginName: h.name, Text: str}
			}
		}
	}()
}

func (h *gateIo) getArticle() (s string, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = errors.New(fmt.Sprintf("%v", e))
		}
	}()

	resp, err := http.DefaultClient.Do(h.getRequest())
	if err != nil {
		log.Error("failed to load url", zap.String("url", url), zap.Error(err))
		return
	}
	if resp.StatusCode != http.StatusOK {
		log.Error("The request response is incorrect", zap.String("url", url), zap.Int("status", resp.StatusCode))
		return
	}
	doc, err := htmlquery.Parse(resp.Body)
	if err != nil {
		log.Error("failed to load doc", zap.String("url", url), zap.Error(err))
		return "", err
	}
	node := htmlquery.FindOne(doc, `//*[@id="lcontentnews"]/div[1]/div[1]/a/h3`)
	return htmlquery.InnerText(node), nil
}

func (h *gateIo) getRequest() *http.Request {
	payload := strings.NewReader("cate_query=voting")

	r, err := http.NewRequest("POST", url, payload)
	if err != nil {
		log.Fatal("failed to New request", zap.String("name", "gate.io"), zap.Error(err))
	}
	r.Header.Set("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Mobile Safari/537.36")
	r.Header.Set("Host", "www.gateio.pro")
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	return r
}
